import { Injectable } from '@nestjs/common';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { Menu } from './entities/menu.entity';
import { Role } from '../role/entities/role.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In, Brackets } from 'typeorm';
import { QueryMenuDto } from './dto/query-menu.dto';
import { isEmptyStr, flatArrayToTree } from 'src/common/utils/common';
import { PageResultDto } from 'src/common/dto';
import { MenuTree } from './dto/menu-tree.dto';
@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(Menu)
    private menuRepository: Repository<Menu>,
  ) {}

  async create(createMenuDto: CreateMenuDto) {
    try{
      const menu = await this.menuRepository.create(createMenuDto);
      await this.menuRepository.save(menu);
      return [true, '菜单添加成功'];
    } catch (error) {
      console.error('Error creating menu:', error);
      return [false, '菜单添加失败'];
    }
  }

  findAll() {
    return `This action returns all menu`;
  }

  findOne(id: number) {
    return `This action returns a #${id} menu`;
  }

  async update(updateMenuDto: UpdateMenuDto) {
    try{
      const menu = await this.menuRepository.create(updateMenuDto);
      await this.menuRepository.save(menu);
      return [true, '菜单更新成功'];
    } catch (error) {
      console.error('Error updating menu:', error);
      return [false, '菜单更新失败'];
    }
  }

  async remove(IdArr: Array<string>) {
    try{
      await this.menuRepository.update(
        { Id: In(IdArr) },{ deleted: 1 }
      );
      return [true, '菜单删除成功'];
    } catch (error) {
      console.error('Error deleting menu:', error);
      return [false, '菜单删除失败'];
    }
  }

  async GetMenuList(query: QueryMenuDto) {
    try{
      let menus = await this.menuRepository.createQueryBuilder('menu')
      .where('menu.Deleted = :Deleted', { Deleted: 0 })
      .andWhere(new Brackets(qb => {
        if (!isEmptyStr(query.Id)) {
          qb.andWhere('menu.Id = :Id', { Id: query.Id });
        }
      }))
      .andWhere(new Brackets(qb => {
        if (!isEmptyStr(query.pid)) {
          qb.andWhere('menu.pid = :pid', { pid: query.pid });
        }
      }))
      .andWhere(new Brackets(qb => {
        if (!isEmptyStr(query.name)) {
          qb.andWhere('menu.name LIKE :name', { name: `%${query.name}%` });
        }
      }))
      .andWhere(new Brackets(qb => {
        if (!isEmptyStr(query.title)) {
          qb.andWhere('menu.title LIKE :title', { title: `%${query.title}%` });
        }
      }))
      .andWhere(new Brackets(qb => {
        if (!isEmptyStr(query.isShow)) {
          qb.andWhere('menu.isShow = :isShow', { isShow: query.isShow });
        }
      }))
      .skip((query.pageNum - 1) * query.pageSize)
      .take(query.pageSize)
      .orderBy('menu.sort', 'ASC')
      .getMany();
      
      let result = new PageResultDto<MenuTree>();
      result.data = flatArrayToTree(menus);
      result.total = await this.menuRepository.count();
      result.pageNum = query.pageNum;
      result.pageSize = query.pageSize;
      return result;
    } catch (error) {
      console.error('Error fetching menu list:', error);
      return new PageResultDto<MenuTree>();
    }
  }
}
